package com.bw.xiaosy.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.Map;

/**
 * @author Xiaosy
 * @date 2017-03-17 14:04
 */
@Controller
public class HomeController {

    @GetMapping({"/","/index"})
    public String index()
    {
        return "/index";
    }

    @GetMapping("/login")
    public String loginUrl()
    {
        return "/login";
    }
    @GetMapping("/logout")
    public String logout()
    {
        Subject currentUser = SecurityUtils.getSubject();
        if(currentUser.isAuthenticated())
        {
            currentUser.logout();
        }
        return "/login";
    }
    @PostMapping(value = "/login")
    public String login(String username,String password,Map<String, Object> map)
    {
        System.out.println("HomeController.login()");
        String msg = null;
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        Subject currentUser = SecurityUtils.getSubject();
        try {
            currentUser.login(token);
        }catch (UnknownAccountException e1)
        {
            System.out.println("UnknownAccountException -- > 账号不存在：");
            msg = "UnknownAccountException -- > 账号不存在：";
        }catch (IncorrectCredentialsException e2)
        {
            System.out.println("IncorrectCredentialsException -- > 密码不正确：");
            msg = "IncorrectCredentialsException -- > 密码不正确：";
        }
        if(msg == null)
        {
            return "/index";
        }
        map.put("msg", msg);
        return "/login";
    }
}
